<?php
class UserForm extends CFormModel{
	public $oldpassword;
	public $username;
	public $password;
	public $confirm;
	public $email;
	public $verifyCode;
	public $error;
	
	public function rules()
	{
		$message ="<span class='ui-icon ui-icon-alert'></span><span class='message'>". Yii::t('yii','Vui lòng nhập {attribute}.')."</span>";
		return array(		
			array('username, password, confirm, oldpassword, email,verifyCode', 'required', 'message'=>$message),
		//	array('password', 'compare', 'compareAttribute'=>'confirm','message'=>'Mật khẩu xác nhận không khớp'),   // here you say that the password must be the same as conf_password
			/*array('confirm', 'safe')*/
				array('verifyCode','required','on'=>'register'),
			array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
		);
	}
	
	public function attributeLabels()
	{
		return array(
			'username'=>'Tên đăng nhập',
		'oldpassword' => 'Mật khẩu củ',
		'password'=>'Mật khẩu',
		'confirm'=>'Xác nhận mật khẩu',
		'email'=>'Email',
		'verifyCode'=>'Captcha',
		);
	}

	public function activeCaptcha()
    {
        $code = Yii::app()->controller->registerAction('captcha')->verifyCode;
        if ($code != $this->verifyCode)
            $this->addError('verifyCode', 'Mã Captcha không hợp lệ');
    }
    
	public function register(){
		if($this->validate()){
			$user = new Tbuser;
			$user->UserName = $this->username;
			$user->Password = $this->password;
			$user->Email = $this->email;
			$user->IdGroupUser = 3;
			$user->Icon = "user.png";
			$user->Salt = Encrypt::generateNumber();
			$user->Password = Encrypt::encript($user->Password, $user->Salt );
			$strValidate = $user->ValidateCreate();
			if($strValidate === ""){
				if( $user->save()){
					return "";
				}else{
					print_r( $user->errors);
					die();
				}
			}
			return $strValidate;
		}else{
			$this->activeCaptcha();
			return false;
		}
	}
	
	public function changepass(){
		$user = Tbuser::model()->findByFK(MyConstans::getUserId());
		if($user===null){
			$this->error = "Chưa đăng nhập";
			return;
		}
		
		if(Encrypt::decript($this->oldpass, $user->Salt, $user->Password)){
			Encrypt::encodePassword($user);
			$user->update();
			$this->error = "";
			return ;
		}
		
		$this->error = "Mã xác thực không hợp lệ"; 
	}
}